package com.andy.qhb.game;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.qhb.entity.UsrFabLog;
import com.andy.qhb.entity.UsrQiangbLog;
import com.andy.qhb.utils.GoConstant;
import com.google.common.collect.Lists;

/**
 * 代表一个红包实体
 * @author cuiwm
 *
 */
public class QhbGame implements Serializable{

	private static Logger logger = LoggerFactory.getLogger(QhbGame.class);
	
	private static final long serialVersionUID = 1L;

	private int status;
	private int id;
	private Long creatTime;
	
	private transient Room room;
	private int coin;
	private Integer num;
	private Integer lei;
	private transient GameUser creater;
	private transient ThreadLocalRandom random = ThreadLocalRandom.current();
	private int[] coins;
	
	private UsrQiangbLog[] qiangbLogs;
	
	int sum;
	int[] ints;
	AtomicInteger currNum;
	AtomicBoolean isReward; // 是否结算完成
	
	public QhbGame(int coin, Integer num, Integer lei) {
		id = GameConf.genId();
		this.coin = coin;
		this.setNum(num);
		this.lei = lei;
		this.setCreatTime(System.currentTimeMillis()/1000);
		
		// 初始化红包
		initPack();
		
//		TimerManager.schedule(()->{
//			if(!isEnd()) {
//				end();
//				rebackCoin();
//			}
//			return null;
//		}, 180*1000);
		
	}
	
	/**
	 * 退还剩余的金币
	 */
	@SuppressWarnings("unused")
	private void rebackCoin() {
		int dealCoin = coin;
		for(int i=0;i<coins.length-1;i++){
			dealCoin -= coins[i];
		}
		GameUtils.userCoinLog(creater, dealCoin, 4,getId());
	}

	private void initPack() {
		sum = 0;
		ints = new int[num];
		coins = new int[num];
		for (int i = 0; i < num; ++i) {
			ints[i] = random.nextInt(num,coin*2);
			sum += ints[i];
        }
		currNum = new AtomicInteger(0);
		isReward = new AtomicBoolean(false);
		qiangbLogs = new UsrQiangbLog[num];
	}

	public void setCreater(GameUser creater){
		this.creater = creater;
	}
	
	public int getId(){
		return id;
	}

	public void end(){
		status = -1;
	}
	
	public boolean isEnd(){
		return status == -1;
	}

	public Integer getNum() {
		return num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}

	public Integer getLei() {
		return lei;
	}

	public UsrFabLog toEntity() {
		UsrFabLog fabLog = new UsrFabLog((long)id);
		fabLog.setUid(creater.getId());
		fabLog.setFname(creater.getNickName());
		fabLog.setRoomId(room.getId());
		fabLog.setCoin(coin);
		fabLog.setNum(num);
		fabLog.setRemark(String.valueOf(lei));
		
		return fabLog;
	}

	public int[] nextCoin(GameUser user) {
		int cur = currNum.getAndIncrement();
		int result = 0;
		if(cur == num-1){
			result = coin;
			for(int i=0;i<coins.length-1;i++){
				result -= coins[i];
			}
			if(result == 0) {
				result = 1;
			}
			coins[cur] = result;
			end();
		}else if(cur<num-1){
			int coinInt = (ints[cur]*10000/sum);
			coins[cur] = coinInt*coin/10000;
			if(coins[cur] == 0) {
				coins[cur] = 1;
			}
			result = coins[cur];
		}
		return new int[]{cur,result};
	}
	
	public boolean reward() {
		boolean isDone = true;
		for(UsrQiangbLog qb:qiangbLogs){
			if(qb == null){
				isDone = false;
				break;
			}
		}
		if(!isDone) return false;
		
		if(isReward.compareAndSet(false, true)) {
			if(room.getType() == GoConstant.GAME_TYPE_S) {
				rewardSaolei();
			}else if(room.getType() == GoConstant.GAME_TYPE_J){
				rewardJinqiang();
			}
			return true;
		}
		return false;
	}

	private void rewardJinqiang() {
		boolean[] reInds = new boolean[num]; // 中雷者
		boolean[] isZhong = countZl(reInds);
		
		int count = isZhong.length; // 雷数
		boolean isAllZhong = true;
		for(int i=0;i<isZhong.length;i++){
			if(!isZhong[i]) {
				isAllZhong = false;
				break;
			}
		}
		int zcount = 0; // 中雷个数
		for(int i=0;i<num;i++){
			if(reInds[i]){
				zcount++;
			}
		}
		logger.info("禁抢中雷情况：{}-{}-{}",count,zcount,isAllZhong);
		if(num == 6 && zcount == 0) {
			// 6包不中
			if(count > 2 && count < 6) {
				int dealCoin = GameConf.jqFbReward[20+count-3]*getCoin()/10;
				GameUtils.userCoinLog(creater, dealCoin, 13, id);
			}
		}
		if(!isAllZhong) return;
		if(num == 5) {
			if(count == 1) {
				// 5包单雷
				int dealCoin = GameConf.jqFbReward[zcount-1]*getCoin()/10;
				GameUtils.userCoinLog(creater, dealCoin, 9, id);
			}else if(count > 1){
				// 5包连环雷
				int dealCoin = GameConf.jqFbReward[11+count-2]*getCoin()/10;
				GameUtils.userCoinLog(creater, dealCoin, 11, id);
			}
		}else if(num == 6) {
			if(count == 1) {
				// 6包单雷
				int dealCoin = GameConf.jqFbReward[5+zcount-1]*getCoin()/10;
				GameUtils.userCoinLog(creater, dealCoin, 10, id);
			}else if(count > 1){
				// 6包连环雷
				int dealCoin = GameConf.jqFbReward[15+count-2]*getCoin()/10;
				GameUtils.userCoinLog(creater, dealCoin, 12, id);
			}
		}
		
	}
	
	private boolean[] countZl(boolean[] reInds) {
		int count = 0; // 雷数
		int leiT = lei;
		int[] leiA = new int[9]; // 具体雷数
		while(leiT > 0){
			leiA[count++] = leiT%10;
			leiT = leiT/10;
		}
		
		boolean[] isZhong = new boolean[count]; // 中雷情况
		for(int i=0;i<coins.length;i++){
			int co = coins[i];
			int v = co % 10;
			for(int j=0;j<count;j++){
				if(v == leiA[j]){
					isZhong[j] = true;
					reInds[i] = true;
					break;
				}
				
			}
		}
		return isZhong;
	}

	private void rewardSaolei() {
		boolean[] reInds = new boolean[num]; // 中雷者
		boolean[] isZhong = countZl(reInds);
		
		int count = isZhong.length;
		boolean isAllZhong = true;
		for(int i=0;i<isZhong.length;i++){
			if(!isZhong[i]) {
				isAllZhong = false;
				break;
			}
		}
		int zcount = 0; // 中雷个数
		if(isAllZhong){
			for(int i=0;i<num;i++){
				if(reInds[i]){
					zcount++;
					// 中雷
					qiangbLogs[i].setRemark("中雷");
					GameUtils.reward(qiangbLogs[i].getUid(),count,this);
				}
			}
			// 发包奖励
			if(zcount >= 3) {
				RewardUtil.rewardFb(zcount,count,creater, this);
			}
		}
		
		logger.info("扫雷中雷情况：{}-{}-{}",count,zcount,isAllZhong);
		
	}

	public GameUser creater() {
		return creater;
	}
	
	public int getCoin(){
		return coin;
	}

	public List<Map<String,Object>> qlogs() {
		List<Map<String,Object>> list = Lists.newArrayList();
		for(UsrQiangbLog qb:qiangbLogs){
			if(qb != null){
				list.add(qb.toMap());
			}
		}
		return list;
	}
	
	public void addQlog(UsrQiangbLog qiangbLog){
		qiangbLogs[qiangbLog.getQorder()] = qiangbLog;
	}

	public boolean isBy(GameUser user) {
		for(UsrQiangbLog qb:qiangbLogs){
			if(qb != null && qb.getUid().equals(user.getId())){
				return true;
			}
		}
		return false;
	}

	public Room room() {
		return room;
	}

	public void setRoom(Room room) {
		this.room = room;
	}

	public Long getCreatTime() {
		return creatTime;
	}

	public void setCreatTime(Long creatTime) {
		this.creatTime = creatTime;
	}
	
	
	private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeInt(room.getId());
//        out.writeLong(creater.getId());
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        room = Global.getRoom(in.readInt());
    }


}
